package Dispatcher;

import java.io.*;
import java.net.*;

public class CommunicationsThread extends Thread{

	private GroupDispatcher gd;
	private Socket socket;
	private int index;
	private BufferedReader in;
	private PrintWriter out;
	
	
	public CommunicationsThread(GroupDispatcher gd) {
		this.gd = gd;
	}
	
	public synchronized String receiveMessage() {
		String msg;
		try {
			msg = this.in.readLine();
			return msg;
		} catch (SocketException e2) {
			System.out.println("Done");
			System.exit(0);
		} catch (IOException e) {
			e.printStackTrace(System.err);
			System.exit(1);
		}
		return "Failed";
	}
	
	public synchronized int activateSocket() {
		try {
			this.socket = this.gd.serverSocket.accept();
		} catch (IOException e1) {
			System.out.println("Cannot accept connection from elevator");
			return -1;
		}
		
		try {
			this.out = new PrintWriter(socket.getOutputStream(), true);
			this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

		} catch (IOException e) {
			System.out.println("Error Accepting: " + this.index);
			return -1;
		}
		return 0;
	}
	
	@Override
	public void run() {
		//accept phase
		int ret = this.activateSocket();
		if (ret == -1) {
			return;
		}
		this.gd.openSockets++;
		//read phase
		String msg;
		while((msg = this.receiveMessage()) != null) {
			gd.handle(msg, this.out);
		}
	}	
}
